package top.kaoshanji.ch02;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 代码清单 ch02-05：AsynchronousFileChannel回调式示例(2.5.2节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/13 18:36
 */
public class AsynchronousFileChannel2Demo {

    private static final Logger logger = LogManager.getLogger(AsynchronousFileChannel2Demo.class);

    public static void main(String[] args) {
        logger.info("...代码清单 ch02-05：AsynchronousFileChannel回调式示例(2.5.2节)...");

        try {
            Path file = Paths.get("D:\\works\\workspace\\readme.txt");

            // 异步打开文件
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(file);

            ByteBuffer buffer = ByteBuffer.allocate(100_000);

            // 从通道中读取数据
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {

                // 读取完成时的回调方法
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("Bytes read [" + result + "]");
                }

                @Override
                public void failed(Throwable exception, ByteBuffer attachment) {
                    System.out.println(exception.getMessage());
                }
            });

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }


    }

}
